package stack;

import java.util.Iterator;

public class LinkedListStack<E> implements Stack<E>,Iterable{
    private  Node head = new Node(null,null);
    private int capacity;
    private  int size =0;

    public LinkedListStack(int capacity) {
        this.capacity = capacity;
    }

    @Override
    public boolean push(E value)
    {
        if(isFull()){
            return false;
        }
        head.next = new Node(value,head.next);
        size++;
        return true;
    }

    @Override
    public E pop()
    {
        if(isEmpty()){
            return null;
        }
        Node first = head.next;
        head.next = first.next;
        size--;
        return first.val;
    }

    @Override
    public E peek() {
        if(isEmpty()){
            return null;
        }
        Node first = head.next;
        return first.val;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public boolean isFull() {
        return capacity == size;
    }

    @Override
    public Iterator iterator() {
        return new Iterator() {
            Node p = head.next;
            @Override
            public boolean hasNext() {
                return p!=null;
            }

            @Override
            public Object next() {
                E val = p.val;
                p = p.next;
                return val;
            }
        };
    }

    class Node{
        E val;
        Node next;

        public Node(E val, Node next) {
            this.val = val;
            this.next = next;
        }
    }
    }

